package com.huang.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huang.constant.Common;
import com.huang.dto.MenuRoleDto;
import com.huang.entity.Menu;
import com.huang.mapper.MenuDao;
import com.huang.service.MenuService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author han
 * @since 2021-10-14 11:05:07
 */
@Service
@Transactional
public class MenuServiceImpl extends ServiceImpl<MenuDao, Menu> implements MenuService {

    @Resource
    private MenuDao menuDao;
    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public List<Menu> findByRoleIds(List<String> roleIds) {
        return menuDao.findByRoleIds(roleIds);
    }

    @Override
    public List<MenuRoleDto> findUrlAndRole() {
        List<MenuRoleDto> list = menuDao.findUrlAndRole();
        List<String> urlList = list.stream().map(MenuRoleDto::getUrl).distinct().collect(Collectors.toList());
        Map<String, String> resourceMap = new HashMap<>();
        list.forEach(mr -> urlList.forEach(url -> {
            if (StrUtil.equals(mr.getUrl(), url)) {
                String code = resourceMap.get("url");
                code = StrUtil.isBlank(code) ? mr.getRoleCode() : code + (mr.getRoleCode() + ",");
                resourceMap.put(url, code);
            }
        }));

        redisTemplate.opsForHash().putAll(Common.SystemConfig.OAUTH_URLS, resourceMap);
        return list;
    }
}
